<style lang="less">
</style>
<template>
  <!--领头羊线路-->
  <div>
    <!--工具条-->
    <search-bar style="height: 90px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="线路起点">
            <el-input  v-model="searchCondition.LIKE_startAddrName"
                       placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="线路终点">
            <el-input  v-model="searchCondition.LIKE_endAddrName"
                       placeholder=""></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="领头羊姓名">
            <el-input  v-model="searchConditionEx.LIKE_truckBellwetherRealName"
                       placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="领头羊电话">
            <el-input  v-model="searchConditionEx.LIKE_truckBellwetherPhone"
                       placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="领头羊状态">
            <el-select v-model="searchConditionEx.LIKE_truckBellwetherStatus" placeholder="请选择启用状态">
              <el-option v-for="item in $store.getters.INDICATOR"
                         :key="item.dictVal"
                         :label="item.cnDictValname  == '是'? '已启用':'未启用'"
                         :value="item.dictVal"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </search-bar>
    <!-- 操作 openDialog3-->
    <el-col :span="24" style="margin-bottom: 10px">
      <el-button type="danger" @click="btnDeleteBatch" style="float: left">批量删除</el-button>
      <el-button type="primary" @click="dialogTruckBellwether" style="float: left">新增线路</el-button>
      <el-button type="primary" @click="resetSearchCondition" style="float: right">重置</el-button>
      <el-button type="primary" @click="searchTableList" style="float: right;">查询</el-button>
    </el-col>
    <!-- 表格-->
    <el-table highlight-current-row border
              :data="tableData"
              v-loading="listLoading"
              @sort-change="sortChange"
              @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" label="序号" width="60" align="center">
      </el-table-column>
      <el-table-column prop="startCity" label="线路起点" min-width="200">
        <template slot-scope="scope">
          <label>{{scope.row.startProvince}}{{scope.row.startCity}}</label>
        </template>
      </el-table-column>
      <el-table-column prop="endCity" label="线路终点" min-width="200">
        <template slot-scope="scope">
          <label>{{scope.row.endProvince}}{{scope.row.endCity}}</label>
        </template>
      </el-table-column>
      <el-table-column prop="truckBellwetherAccount" label="领头羊账号" width="150">
      </el-table-column>
      <el-table-column prop="truckBellwetherRealName" label="领头羊姓名" width="120">
      </el-table-column>
      <el-table-column prop="truckBellwetherPhone" label="领头羊电话" width="150">
      </el-table-column>
      <el-table-column prop="truckBellwetherStatus" label="领头羊状态" width="150">
        <template slot-scope="scope">
          <label v-if="scope.row.truckBellwetherStatus === 111002001">已启用</label>
          <label v-if="scope.row.truckBellwetherStatus === 111002002">未启用</label>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button type="danger" style="margin-left: 5px;margin-top: 5px"
                     @click="btnDelete(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>
    <!--新增零头羊线路弹窗-->
    <el-dialog title="新增线路" width="850px" :visible.sync="dialogVisible"
               :close-on-click-modal="false" @close="resetInfoForm" class="ue-dialog-edit">
      <el-form :inline="true" :key="dialogKey" :model="objInfo" :rules="objInfoRules" label-width="120px" ref="objInfo">
        <el-row>
          <el-col :span="24">
            <el-form-item label="起始范围" prop="startProvinceId">
              <el-select v-model="objInfo.startProvinceId" filterable  @change="changeStartProvince" value-key="id" placeholder="请选择始发-省" style="width: 200px">
                <el-option
                  v-for="(item,index) in provinceList"
                  :label="item.name"
                  :value="item.id" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="startCitySelect" filterable value-key="id" placeholder="非直辖市,请选择始发-市" :disabled="isSpecialStart" style="width: 330px">
                <el-option
                  v-for="(item,index) in startCityList"
                  :label="item.name"
                  :value="item.id +'-'+item.name" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="目的范围" prop="endProvinceId">
              <el-select v-model="objInfo.endProvinceId" filterable @change="changeEndProvince" value-key="id" placeholder="请选择目的-省" style="width: 200px">
                <el-option
                  v-for="(item,index) in provinceList"
                  :label="item.name"
                  :value="item.id" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="endCitySelect" filterable  multiple collapse-tags value-key="id" placeholder="非直辖市,请选择目的-市" :disabled="isSpecialEnd" style="width: 330px">
                <el-option
                  v-for="(item,index) in endCityList"
                  :label="item.name"
                  :value="item.id +'-'+item.name" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分配领头羊" prop="truckBellwetherId">
              <el-select v-model="objInfo.truckBellwetherId"
                         filterable
                         remote
                         reserve-keyword
                         placeholder="请输入关键词(姓名/电话/账号)"
                         :remote-method="remoteMethod"
                         :loading="selectLoading"
                         value-key="id" style="width: 530px">
                <el-option
                  v-for="(item,index) in truckBellwetherData"
                  :label="item.realName"
                  :value="item.id" :key="index">
                  <span style="float: left">{{ item.realName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.account }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: left;margin-left: 120px">
        <el-button @click.native="resetInfoForm">关闭</el-button>
        <el-button type="primary" @click.native="handleSubmitBatch" :loading="submitLoading" :disabled="submitLoading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchTruckBellwetherList,
  searchTruckBellwetherLinesListManage,
  saveTruckBellwetherLines,
  deleteInfoLinesById
} from '../../../api/v3/TruckBellwether';
import { resetObjNull, objToFilter, getSelectObect } from '../../../lib/util.js';
import {
  getAddresses
} from '../../../api/system/MarkCargo';

export default {
  data () {
    return {
      activeName: 'first',
      // 领头羊线路
      searchConditionEx: {
        'LIKE_truckBellwetherRealName': null,
        'LIKE_truckBellwetherPhone': null,
        'LIKE_truckBellwetherStatus': null
      },
      searchCondition: {
        'LIKE_startAddrName': null, // 路线起点
        'LIKE_endAddrName': null // 路线终点
      },
      sels: [],
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: 'createdDate',
      sortOrder: 'descending',
      listLoading: false,

      // 新增领头羊线路弹窗
      submitLoading: false,
      dialogVisible: false,
      dialogKey: 0,
      objInfo: {},
      objInfoRules: {
        startProvinceId: [
          {required: true, message: '请输入始发-省', trigger: 'blur'}
        ],
        endProvinceId: [
          {required: true, message: '请输入目的-省', trigger: 'blur'}
        ],
        truckBellwetherId: [
          {required: true, message: '请选择领头羊', trigger: 'blur'}
        ]
      },
      // 直辖市地址
      addressDictSpecial: [111, 112, 131, 150],
      isSpecialStart: false,
      isSpecialEnd: false,
      provinceList: [],
      startCityList: [],
      endCityList: [],
      startCitySelect: null, // 始发-市
      endCitySelect: [], // 目的-市 多选
      selectLoading: false,
      truckBellwetherData: []
    };
  },
  watch: {},
  methods: {
    // 加载领头羊列表
    remoteMethod (query) {
      if (query !== '') {
        this.selectLoading = true;
        setTimeout(() => {
          searchTruckBellwetherList({
            filters: 'EQ_organizationId=' + this.$store.state.currentOrganizationId + ';EQ_status=111002001;LIKE_realName=' + query + '_OR_LIKE_phone=' + query + '_OR_LIKE_account=' + query}).then(res => {
            this.selectLoading = false;
            this.truckBellwetherData = res.data;
          });
        }, 200);
      } else {
        this.truckBellwetherData = [];
      }
    },
    // 初始化载入省份
    getAddressProvince () {
      getAddresses('156').then((res) => {
        if (res.data.detailModelList !== '' && res.data.detailModelList !== null) {
          this.provinceList = res.data.detailModelList;
        }
      });
    },
    // 起始省-选择时触 发
    changeStartProvince (pid) {
      this.isSpecialStart = false;
      if (this.addressDictSpecial.contains(pid)) {
        this.isSpecialStart = true;
      }
      if (pid) {
        this.objInfo.startProvinceId = pid;
        // 清除市相关数据
        this.startCitySelect = null;
        this.startCityList = [];
        getAddresses(pid).then((res) => {
          if (res.data.detailModelList !== '' && res.data.detailModelList !== null) {
            this.startCityList = res.data.detailModelList;
          }
        });
      }
    },
    // 目的省-选择时触 发
    changeEndProvince (pid) {
      this.isSpecialEnd = false;
      if (this.addressDictSpecial.contains(pid)) {
        this.isSpecialEnd = true;
      }
      if (pid) {
        this.objInfo.endProvinceId = pid;
        // 清除市相关数据
        this.endCitySelect = [];
        this.endCityList = [];
        getAddresses(pid).then((res) => {
          if (res.data.detailModelList !== '' && res.data.detailModelList !== null) {
            this.endCityList = res.data.detailModelList;
          }
        });
      }
    },
    // --------------零头羊线路-----------
    // 多选操作
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchTableList();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchTableList();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchTableList();
    },
    // 领头羊线路查询条件重置
    resetSearchCondition () {
      resetObjNull(this.searchCondition);
      resetObjNull(this.searchConditionEx);
    },
    // 领头羊线路查询
    searchTableList () {
      let filters = objToFilter(this.searchCondition);
      if (this.searchConditionEx.LIKE_truckBellwetherRealName) {
        filters += ';LIKE_truckBellwether.realName=' + this.searchConditionEx.LIKE_truckBellwetherRealName;
      }
      if (this.searchConditionEx.LIKE_truckBellwetherPhone) {
        filters += ';LIKE_truckBellwether.phone=' + this.searchConditionEx.LIKE_truckBellwetherPhone;
      }
      if (this.searchConditionEx.LIKE_truckBellwetherStatus) {
        filters += ';EQ_truckBellwether.status=' + this.searchConditionEx.LIKE_truckBellwetherStatus;
      }
      this.listLoading = true;
      searchTruckBellwetherLinesListManage({
        filters: filters,
        size: this.pageSize,
        page: this.currentPage - 1,
        sort: this.sortProp === null ? 'createdDate,desc' : (this.sortProp + (this.sortOrder === 'ascending' ? ',asc' : ',desc'))
      }).then(res => {
        if (res.status === 200) {
          this.tableData = res.data;
          this.total = Number(res.headers['x-total-count']);
        };
      });
      this.listLoading = false;
    },
    // 新增领头羊线路弹窗
    dialogTruckBellwether () {
      this.dialogVisible = true;
    },
    // 新增路线表单重置
    resetInfoForm () {
      this.dialogVisible = false;
      this.dialogKey = Math.random() - 0.5;
      for (let p in this.objInfo) {
        if (this.objInfo[p] instanceof Array) {
          this.objInfo[p] = [];
        } else {
          this.objInfo[p] = null;
        }
      };
    },
    // 新增领头羊线路保存
    handleSubmitBatch () {
      this.$refs['objInfo'].validate((valid) => {
        if (valid) {
          if (!this.startCitySelect) {
            // 非直辖市-起点必须到地级市
            if (!this.addressDictSpecial.contains(this.objInfo.startProvinceId)) {
              return this.$message.error('起始城市有误，非直辖市至少选到市一级！');
            }
          }
          if (!this.endCitySelect[0]) {
            // 非直辖市-起点必须到地级市
            if (!this.addressDictSpecial.contains(this.objInfo.endProvinceId)) {
              return this.$message.error('目的城市有误，非直辖市至少选到市一级！');
            }
          }
          // 后台根据 逗号拆出不同城市，在根据横杠拆出 城市id，城市名
          this.objInfo.startProvince = getSelectObect(this.objInfo.startProvinceId, 'id', this.provinceList).name;
          if (!this.addressDictSpecial.contains(this.objInfo.startProvinceId)) {
            this.objInfo.startAddrName = this.startCitySelect;
          }
          this.objInfo.endProvince = getSelectObect(this.objInfo.endProvinceId, 'id', this.provinceList).name;
          if (!this.addressDictSpecial.contains(this.objInfo.endProvinceId)) {
            this.objInfo.endAddrName = this.endCitySelect.join(',');
          }
          this.submitLoading = true;
          saveTruckBellwetherLines(this.objInfo).then((res) => {
            this.$message.success('新增领头羊线路操作成功！');
            this.dialogVisible = false;
            this.startCitySelect = null;
            this.endCitySelect = [];
            this.searchTableList();
          }).catch((res) => {
            this.$message.error(res.response.data.message);
          });
          this.submitLoading = false;
        } else {
          return false;
        }
      });
    },
    // 删除领头羊线路
    btnDelete (id) {
      this.$confirm('您确认删除该领头羊线路?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        deleteInfoLinesById(id).then(res => {
          if (res.status === 200) {
            this.$message('操作成功');
            this.searchTableList();
          }
        }).catch((res) => {
          this.$message.error(res.response.data.message);
        });
      });
    },
    // 批量删除
    btnDeleteBatch () {
      if (this.sels.length <= 0) {
        this.$message.error('请选择数据');
        return;
      };
      let ids = this.sels.map(o => o.id);
      this.$confirm('您确认删除该领头羊线路？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteInfoLinesById(ids).then(res => {
          if (res.status === 200) {
            this.$message('操作成功');
            this.searchTableList();
          }
        }).catch((res) => {
          this.$message.error(res.response.data.message);
        });
      });
    }
  },
  // 初始化数据
  mounted () {
    this.$store.commit('initDict');
    this.searchTableList();
    this.getAddressProvince();
  }
};
</script>
